<?php
error_reporting(E_ERROR | E_PARSE);
session_start();
include("load-settings.php");

if(!isset($_SESSION['user']))
	header("Location: login.php");

$user = $_SESSION['user'];
$order = mysql_real_escape_string($_GET['id']);

$result = mysql_query("SELECT * FROM user WHERE id = $user");
$row = mysql_fetch_array($result);
$username = $row['username'];
$access_level = $row['type'];

$result = mysql_query("SELECT * FROM order_record WHERE id = $order");
$row = mysql_fetch_array($result);
$customer = $row['user'];

if($access_level == 0 && $user != $customer)
	header("Location: home.php");

$result = mysql_query("SELECT * FROM user WHERE id = ".$row['user']) or die(mysql_error());
$row = mysql_fetch_array($result);


$booster_result = mysql_query("SELECT * FROM booster_order WHERE order_record = $order AND active = 1") or die(mysql_error());

if(mysql_num_rows($booster_result) == 0)
{
	$booster_row = array();
	$booster_row['wins'] = 0;
	$booster_row['losses'] = 0;
	$booster_row['percent'] = 0;

	$booster = "No one";
	$id = 0;
}
else
{
	$booster_row = mysql_fetch_array($booster_result);
	
	$detail_result = mysql_query("SELECT * FROM user WHERE id = ".$booster_row['booster']);
	$detail_row = mysql_fetch_array($detail_result);
	$booster = $detail_row['username'];
	$id = $booster_row['id'];
}

if($access_level == 1 && $booster_row['booster'] != $user)
{
	header("Location: home.php");
}


$order_result = mysql_query("SELECT * FROM order_record WHERE id = $order");

if(mysql_num_rows($order_result) == 0)
	header("Location: home.php");

$order_row = mysql_fetch_array($order_result);

$summoner = $order_row['summoner'];
$region = $order_row['region'];
$user_name = $order_row['username'];
$password = $order_row['password'];

$result = mysql_query("SELECT DISTINCT booster FROM booster_order WHERE order_record = ".$order_row['id']) or die(mysql_error());

require_once("unirest/lib/Unirest.php");

$returnArray = array();

$result = mysql_query("SELECT * FROM match_history WHERE order_id = $order ORDER BY timestamp DESC") or die(mysql_error());

$y = 0;

$all_wins = 0;
$all_losses = 0;

while($row = mysql_fetch_array($result))
{
	array_push($returnArray, $row);
	if($row['win'] == 0)
		$all_losses++;
	else
		$all_wins++;
	$y++;
}
$pages = ceil($y/5);

$tier = "";
$rank = "";
$last_match_result = mysql_query("SELECT * FROM match_history WHERE order_id = ".$order_row['id']." ORDER BY timestamp DESC LIMIT 1") or die(mysql_error());
//$tier = $row['start_tier'];
//$rank = $row['start_division'];
if(mysql_num_rows($last_match_result) == 0)
{
	$lp = $order_row['beginning_lp'];
	$tier = $order_row['start_tier'];
	$rank = numberToRoman($order_row['start_division']);
}
else
{
	$last_match = mysql_fetch_array($last_match_result);
	$lp = $last_match['lp_at_end'];
	if($last_match['tier_at_end'] != null && $last_match['tier_at_end'] != "")
	{
		$tier = $last_match['tier_at_end'];
	}
	if($last_match['rank_at_end'] != null && $last_match['rank_at_end'] != "")
	{
		$rank = $last_match['rank_at_end'];
	}

	//$tier = $last_match['tier_at_end'];
	//$rank = $last_match['rank_at_end'];
}
if($tier == "")
{
	$lp = $order_row['beginning_lp'];
	$tier = $order_row['start_tier'];
	$rank = numberToRoman($order_row['start_division']);
}

$x = 0;
$champ_array = array();

while(isset($returnArray[$x]))
{
	$champ_array[$x] = $returnArray[$x]['champion'];
	$x++;
}

$champs = array_count_values($champ_array);

arsort($champs);
$champ_keys = array_keys($champs);

$x = 0;

$win_loss = array();

while(isset($champ_keys[$x]))
{
	$y = 0;
	$win_loss[$x] = array();
	$win_loss[$x]['win'] = 0;
	$win_loss[$x]['loss'] = 0;
	while(isset($returnArray[$y]))
	{
		if($returnArray[$y]['champion'] == $champ_keys[$x])
		{
			if($returnArray[$y]['win'] == 1)
				$win_loss[$x]['win']++;
			else
				$win_loss[$x]['loss']++;
		}
		$y++;
	}
	$x++;
}
$champ_lookup = array();

/*$response = Unirest::get(
  "https://teemojson.p.mashape.com/datadragon/champion",
  array(
    "X-Mashape-Authorization" => "XcM4wvOlSewxmSNGstMYMpkjxvZGc8gx"
  )
);

$decode = json_decode($response->raw_body)->data;
$x = 0;

foreach ($decode as $item)
{
	$champ_lookup[$x] = array();
	$champ_lookup[$x]['id'] = $item->key;
	$champ_lookup[$x]['name'] = $item->id;
	$x++;
}*/
$champ_result = mysql_query("SELECT * FROM champion");

while($champ_row = mysql_fetch_array($champ_result))
{
	array_push($champ_lookup, $champ_row);
}
//var_dump($champ_lookup); die;

//var_dump($champ_lookup[key_to_name($champ_lookup, (string)$returnArray[0]['champion'])]['name']); die;

function key_to_name($products, $needle)
{
   foreach($products as $key => $product)
   {
      if ( $product['id'] === $needle )
         return $key;
   }
   return false;
}
//var_dump($decode->data->summonerLeagues->array[0]); die;
function numberToRoman($num) 
 {
     // Make sure that we only use the integer portion of the value
     $n = intval($num);
     $result = '';
 
     // Declare a lookup array that we will use to traverse the number:
     $lookup = array('M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400,
     'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
     'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
 
     foreach ($lookup as $roman => $value) 
     {
         // Determine the number of matches
         $matches = intval($n / $value);
 
         // Store that many characters
         $result .= str_repeat($roman, $matches);
 
         // Substract that from the number
         $n = $n % $value;
     }
 
     // The Roman numeral should be built, return it
     return $result;
 }

 function romanToNumber($roman)
 {
	 $romans = array(
    'M' => 1000,
    'CM' => 900,
    'D' => 500,
    'CD' => 400,
    'C' => 100,
    'XC' => 90,
    'L' => 50,
    'XL' => 40,
    'X' => 10,
    'IX' => 9,
    'V' => 5,
    'IV' => 4,
    'I' => 1,
);

$result = 0;

foreach ($romans as $key => $value) {
    while (strpos($roman, $key) === 0) {
        $result += $value;
        $roman = substr($roman, strlen($key));
    }
}
return $result;
}

 function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}
?>
<!doctype html>
<html>
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, maximum-scale=1, initial-scale=1, user-scalable=0">

  <!-- Always force latest IE rendering engine or request Chrome Frame -->
  <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">

  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,800">
    <link rel="icon" href="http://www.veteranboosters.com/wp-content/uploads/2014/04/favicon4.png" type="image/x-icon"/>
    <link rel="shortcut icon" href="http://www.veteranboosters.com/wp-content/uploads/2014/04/favicon4.png" type="image/x-icon"/>
  <!-- Use title if it's in the page YAML frontmatter -->
  <title>Veteran Boosters Order Tracking</title>


  <!--[if lt IE 9]>
  <script src="../../javascripts/vendor/html5shiv.js" type="text/javascript"></script>
  <script src="../../javascripts/vendor/excanvas.js" type="text/javascript"></script>
  <![endif]-->
  <link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/font-awesome.css" />
<link rel="stylesheet" href="css/fullcalendar.css" />
<link rel="stylesheet" href="css/jquery.jscrollpane.css" />	
<link rel="stylesheet" href="css/unicorn.css" />

  <link href="stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
  <script src="javascripts/application.js" type="text/javascript"></script>
  <script src="javascripts/bootpag.js"></script>
</head>
<?php
	include("top.php");
?>
<?php
	echo "<!--"; var_dump($champ_keys); echo "-->";
?>
  <div class="container-fluid padded">
    <div class="row-fluid">

      <!-- Breadcrumb line -->

      <div id="breadcrumb">
          <a href="/" title="" class="tip-bottom" data-original-title="Go to Home"><i class="fa fa-home"></i> Home</a>
          <a href="#">Members</a>
          <a href="#" class="current">Overview  </a>
         </div>
    </div>
  </div>

  <div class="container-fluid padded">
    <?php if($access_level == 1)
	{
		echo "<div class='alert alert-info'>".$booster_order_message."</div>";
	}
	else if($access_level == 0)
	{
		echo "<div class='alert alert-info'>".$customer_order_message."</div>";
	}
	?>
	<?php
		if(($access_level == 1 && $booster_row['started'] == 1) || $access_level == 2 || $access_level == 3 || $access_level == 0)
		{
			echo '<div class = "row-fluid"><div class = "col-lg-12"><div class = "box details">';
			echo '<div class = "box-header"><span class = "title">Order details</span></div>';
			echo '<div class="" style = "margin-bottom: 20px"><div class = "content"><table class = "table table-normal">';
			echo '<tr><th>Username</th><th>Password</th><th>Summoner</th><th>Region</th></tr>';
			echo '<tr><td>'.$order_row['username'].'</td><td>'.$order_row['password'].'</td><td>'.$order_row['summoner'].'</td><td>'.strtoupper($region).'</td></tr>';
			echo '</table></div></div></div></div></div>';
		}
		else if($access_level == 1 && $booster_row['started'] == 0)
		{
			echo '<table class = "table table-normal"><tr><td><a class="btn btn-large btn-block btn-green" onclick = "check_confirm(event)" href = "start_order.php?order='.$order.'">Start order</a></td></tr></table>';
		}
			//echo '<div class = "row-fluid"><div class = "col-lg-12">';
			//echo '<a href = "flag.php?id='.$order_row['id'].'" class="btn btn-large btn-block btn-red">Contact Admin (Creates Ticket)</a><br />';
			echo '<table class = "table table-normal"><tr><td width = "50%"><a onclick = "check_confirm(event)" href = "flag.php?id='.$order_row['id'].'" class="btn btn-large btn-block btn-red">Contact Admin (Creates Ticket)</a></td><td><a class="btn btn-large btn-block btn-green" onclick = "check_confirm(event)" href = "complete.php?order='.$order.'">Mark as complete (pending admin verification)</a></td></tr></table>';
			echo '</div>';
		
	?>
	
<!-- order progress and stats boxes -->
<div class="row-fluid">
   <div class="col-lg-6">
      <div class="box details">
         <div class="box-header">
            <span class="title">Order Details: Order ID <?php echo $order; ?></span>
         </div>
         <div class="box-content padded" style="height: 400px;">
                                                                                                     
                             
               <style type="text/css">
                  table#tiers td img { width: 140px; height: 140px; }
               </style>
			   <div class="alert alert-success col-lg-12" style="margin-left: 0; text-align: center;">
			   <?php
			   /*$match_result = mysql_query("SELECT * FROM match_history WHERE order_id = ".$order_row['id']." ORDER BY timestamp DESC LIMIT 1");
				if(mysql_num_rows($match_result) == 0)
					$lp = $order_row['beginning_lp'];
				else
				{
					$match_row = mysql_fetch_array($match_result);
					$lp = $match_row['lp_at_end'];
				}*/
				
							?>
			   <?php
							if($order_row['end_tier'] != null && $order_row['end_tier'] != "")
							{
								?>
			   Beginning stats: <?php echo $order_row['beginning_stats'].", ".$order_row['beginning_lp']." LP"; ?>
			   <?php
							}
							else
							{
								?>
								Beginning stats: <?php echo $order_row['start_tier']." ".$order_row['start_division'].", ".$order_row['beginning_stats'].", ".$order_row['beginning_lp']." LP"; ?>
								<?php
							}
								?>
			   </div>
               <div class="alert alert-success col-lg-12" style="margin-left: 0; text-align: center;">
			   <?php
				  if($order_row['end_tier'] == null || $order_row['end_tier'] == "")
				  {
					  ?>
                  <div class = "span4" style = "min-height: 1px">
                     Wins: <?php echo $all_wins; ?>                  </div>
                  <div class = "span4" style = "min-height: 1px">
                     Defeats: <?php echo $all_losses; ?>                   </div>
				  <div class = "span4" style = "min-height: 1px">
				  <?php if($order_row['previous_tier'] != null && $order_row['previous_tier'] != "") { ?>
				     Desired games: <?php echo $order_row['number_of_wins']; ?> 
					 <?php } else { ?>
                     Desired wins: <?php echo $order_row['number_of_wins']; ?>
					 <?php } ?> </div>
					 <?php
				  }
				else
				{ ?>
				<div style = "float: left">
                     Wins: <?php echo $all_wins; ?>                  </div>
                  <div style = "float: right">
                     Defeats: <?php echo $all_losses; ?>                   </div>
				<?php } ?>
               </div>
               <table id="tiers" style="margin: 0 auto;">
			   <?php
				if($order_row['end_tier'] != null && $order_row['end_tier'] != "")
				{
					echo '
                  <thead>
                     <tr><th>Started</th>
                     <th>Current</th>
                     <th>Desired</th>
                  </tr></thead>
                  <tbody>
                     <tr>
                        <td><img src="/_FILES/images/'.strtolower($order_row['start_tier']).'_'.$order_row['start_division'].'.png"><br><center><small>'.$order_row['start_tier'].' '.numberToRoman($order_row['start_division']).'<br></small></center></td>
                        <td><img src="/_FILES/images/'.strtolower($tier).'_'.romanToNumber($rank).'.png"><br><center><small><b>'.$tier.' '.$rank.'</b><br></small><small>LP: '.$lp.'</small></center></td>
                        <td><img src="/_FILES/images/'.strtolower($order_row['end_tier']).'_'.$order_row['end_division'].'.png"><br><center><small>'.$order_row['end_tier'].' '.numberToRoman($order_row['end_division']).'<br></small></center></td>
                     </tr>
                  </tbody>';
				}
				else
				{
					echo '
                  <thead>
                     <tr>';

					 if($order_row['previous_tier'] != null && $order_row['previous_tier'] != "")
						 echo "<th>Last Season</th>";
					 
                     echo '<th>Current</th>';
                     
                  echo '</tr></thead>
                  <tbody>
                     <tr>';
                        if($order_row['previous_tier'] != null && $order_row['previous_tier'] != "")
					{
						
						if($order_row['previous_tier'] != "UNRANKED" && $order_row['previous_tier'] != "CHALLENGER")
							$temp_rank = 5;
						else
							$temp_rank = 0;
						echo '<td><img src="/_FILES/images/'.strtolower($order_row['previous_tier']).'_'.$temp_rank.'.png"></td>';

					}
						//if($tier != "UNRANKED")
						//{
							echo '<td><img src="/_FILES/images/'.strtolower($tier).'_'.romanToNumber($rank).'.png"><br><center><small><b>'.$tier.' '.$rank.'</b><br></small><small>LP: '.$lp.'</small></center></td>';
						//}
						
                        
                    echo '</tr>
                  </tbody>';

				  
				}
				?>
               </table>
               <br>
			   <?php

							if($order_row['end_tier'] != null && $order_row['end_division'] != '')
							{
								if($order_row['start_tier'] == "Bronze")
									$start_tier_num = 0;
								if($order_row['start_tier'] == "Silver")
									$start_tier_num = 5;
								if($order_row['start_tier'] == "Gold")
									$start_tier_num = 10;
								if($order_row['start_tier'] == "Platinum")
									$start_tier_num = 15;
								if($order_row['start_tier'] == "Diamond")
									$start_tier_num = 20;

								if($order_row['start_division'] == 5)
									$start_tier_num += 0;
								if($order_row['start_division'] == 4)
									$start_tier_num += 1;
								if($order_row['start_division'] == 3)
									$start_tier_num += 2;
								if($order_row['start_division'] == 2)
									$start_tier_num += 3;
								if($order_row['start_division'] == 1)
									$start_tier_num += 4;

								if($order_row['end_tier'] == "Bronze")
									$end_tier_num = 0;
								if($order_row['end_tier'] == "Silver")
									$end_tier_num = 5;
								if($order_row['end_tier'] == "Gold")
									$end_tier_num = 10;
								if($order_row['end_tier'] == "Platinum")
									$end_tier_num = 15;
								if($order_row['end_tier'] == "Diamond")
									$end_tier_num = 20;

								if($order_row['end_division'] == 5)
									$end_tier_num += 0;
								if($order_row['end_division'] == 4)
									$end_tier_num += 1;
								if($order_row['end_division'] == 3)
									$end_tier_num += 2;
								if($order_row['end_division'] == 2)
									$end_tier_num += 3;
								if($order_row['end_division'] == 1)
									$end_tier_num += 4;

								$total_steps = $end_tier_num - $start_tier_num;

								$tier = ucwords(strtolower($tier));
								$rank = romanToNumber($rank);

								if($tier == "Unranked")
									$percent = 0;
								else
								{
									if($tier == "Bronze")
										$tier_num = 0;
									if($tier == "Silver")
										$tier_num = 5;
									if($tier == "Gold")
										$tier_num = 10;
									if($tier == "Platinum")
										$tier_num = 15;
									if($tier == "Diamond")
										$tier_num = 20;

									if($rank == 5)
										$tier_num += 0;
									if($rank == 4)
										$tier_num += 1;
									if($rank == 3)
										$tier_num += 2;
									if($rank == 2)
										$tier_num += 3;
									if($rank == 1)
										$tier_num += 4;

									$tier_num -= $start_tier_num;

									$percent = ($tier_num/$total_steps) * 100;
									
								}
							}
							else
							{
								$net_wins = $booster_row['wins'] - $booster_row['losses'];
								if($net_wins < 0)
									$net_wins = 0;
								$percent = round(($net_wins / $order_row['number_of_wins']) * 100);
							}
			   ?>
               <div class="progress progress-warning progress-striped  active" style="margin-bottom: 0px;" title="<?php echo $percent; ?> %"><div style="width: <?php echo $percent; ?>%;" class="bar"></div></div>
                        <br>
            <div class="modal fade" id="gift-modal">
               <form action="https://www.paypal.com/cgi-bin/webscr" method="post" id="gift-form" class="form-horizontal" onsubmit = "check_specified(event)">
                   <div class="modal-dialog">
                       <div class="modal-content">
                  <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                     <h4>Send Gift For Booster</h4>
                  </div>
                  <div class="modal-body">
                     <div class="control-group" style="margin-bottom: 5px;">
                        <label class="control-label" for="booster-name">Booster:</label>
                        <div class="controls">
                           <select class="input-big" id="booster-name" name="booster-name">
                              <option value="0" label="Not specified">Not specified</option>
							  <?php
									$result = mysql_query("SELECT DISTINCT booster FROM booster_order WHERE order_record = ".$order_row['id']) or die(mysql_error());

									while($row = mysql_fetch_array($result))
									{
										$subresult = mysql_query("SELECT * FROM user WHERE id = ".$row['booster']);
										$subrow = mysql_fetch_array($subresult);
										echo '<option value = "'.$subrow['id'].'" label = "'.$subrow['username'].'">'.$subrow['username'].'</option>';
									}
							  ?>
							   
						 </select>
                        </div>
                     </div>
                     <div class="control-group" style="margin-bottom: 0px;">
                        <label class="control-label" for="gift-value">Gift Value:</label>
                        <div class="controls">
                           <select class="input-big" id="gift-value" name="gift-value">
                              <option value="5" label="$5">$5</option>
                              <option value="10" label="$10">$10</option>
                              <option value="15" label="$15">$15</option>
                              <option value="20" label="$20">$20</option>
                              <option value="25" label="$25">$25</option>
                              <option value="30" label="$30">$30</option>
                              <option value="40" label="$40">$40</option>
                              <option value="50" label="$50">$50</option>
                           </select>
                        </div>
                     </div>
                     <input type="hidden" name="cmd" value="_xclick">
                     <input type="hidden" name="business" value="Admin@VeteranBoosters.com">
                     <input type="hidden" name="item_name" id="name" value="Gift for booster">
                     <input type="hidden" name="item_number" value="3">
                     <input type="hidden" name="amount" id="cost" value="5">
                     <input type="hidden" name="currency_code" value="USD">
                     <input type="hidden" value="order=<?php echo $order; ?>&amp;booster=0" name="custom" id="custom">
                     <input type="hidden" name="notify_url" value="http://veteranboosters.com/confirm_gift.php">
                     <input type="hidden" name="return" value="http://veteranboosters.com/orders/order.php?id=<?php echo $order; ?>">
                     <script>
                        $('#gift-value, #booster-name').on('change',function() {
                           if($(this).attr('id') == 'booster-name') {
                              $('#custom').val('order=<?php echo $order; ?>&booster=' + $(this).val());
                              if($(this).val() > 0)
                                 $('#name').val('Gift for ' + $('#booster-name option:selected').text());
                              else
                                 $('#name').val('Gift for booster');
                           }

                           if($(this).attr('id') == 'gift-value') 
                              $('#cost').val($(this).val());
                        });
                     </script>
                  </div>
                  <div class="modal-footer">
                     <a href="#" class="btn btn-default" data-dismiss="modal">Close</a>
                     <button type="submit" class="btn btn-success btn-xs" id="save">Continue to PayPal</button>
                  </div>
               </form>
            </div>
               </div>
         </div>
            <div id="gifts">
			   
                  <button type="button" class="btn btn-large btn-block btn-green" data-toggle="modal" data-target="#gift-modal"><i class="icon-gift icon-white"></i> Send Gift For Booster!</button>
			   
            </div>
         </div>
      </div>
   </div>
<div class="col-lg-6">
<div class="row-fluid">
<div class="col-lg-12 ">
    <div class="box support">
        <div class="box-header">
            <div class="title">Customer Chat</div>

        </div>

        <div class="box-content">

            <ul class="chat-box" id="refresh" style = "height: 489px">
                <div id="chat-messages-inner">
                    <?php
                    $result = mysql_query("SELECT * FROM order_chat WHERE order_record = $order ORDER BY timestamp DESC");

                    $messages = array();

                    while($row = mysql_fetch_array($result))
                    {
                        $subresult = mysql_query("SELECT * FROM user WHERE id = ".$row['user']);
                        $subrow = mysql_fetch_array($subresult);

                        $row['name'] = $subrow['username'];
                        $row['email'] = $subrow['paypal'];
                        $row['type'] = $subrow['type'];

                        array_push($messages, $row);
                    }

                    $x = 0;

                    while(isset($messages[$x]))
                    {
                        if($messages[$x]['type'] == 0)
                        {
                            echo '<li class="arrow-box-right gray" id="msg-'.$messages[$x]['id'].'">';
                            echo '<div class="avatar"><img class="avatar-small" src="images/avatars/'.$messages[$x]['type'].'.png"></div>';
                            echo '<div class="info"><span class="name"><strong>'.$messages[$x]['name'].'</strong>';
                            echo '<span class="badge badge-gray">customer</span>';

                            if($type == 2 || $type == 3)
                                echo "<span class='badge badge-red' style = 'margin-left: 5px; cursor: pointer;' onclick = 'delete_order_chat(".$messages[$x]['id'].")'>Remove</span>";

                            echo '</span>';
                            echo '<span class="time">'.date("d M Y g:i:sA", $messages[$x]['timestamp']).'</span>';
                            echo '</div>'.stripslashes($messages[$x]['message']).'</li>';
                            echo '<li class="divider"></li>';
                        }
                        else if($messages[$x]['type'] == 1)
                        {
                            echo '<li class="arrow-box-left gray" id="msg-'.$messages[$x]['id'].'">';
                            echo '<div class="avatar"><img class="avatar-small" src="images/avatars/'.$messages[$x]['type'].'.png"></div>';
                            echo '<div class="info"><span class="name"><strong>'.$messages[$x]['name'].'</strong>';
                            echo '<span class="badge badge-blue">booster</span>';

                            if($type == 2 || $type == 3)
                                echo "<span class='badge badge-red' style = 'margin-left: 5px; cursor: pointer;' onclick = 'delete_order_chat(".$messages[$x]['id'].")'>Remove</span>";

                            echo '</span>';
                            echo '<span class="time">'.date("d M Y g:i:sA", $messages[$x]['timestamp']).'</span>';
                            echo '</div>'.stripslashes($messages[$x]['message']).'</li>';
                            echo '<li class="divider"></li>';
                        }
                        else if($messages[$x]['type'] == 2)
                        {
                            echo '<li class="arrow-box-left gray" id="msg-'.$messages[$x]['id'].'">';
                            echo '<div class="avatar"><img class="avatar-small" src="images/avatars/'.$messages[$x]['type'].'.png"></div>';
                            echo '<div class="info"><span class="name"><strong>'.$messages[$x]['name'].'</strong>';
                            echo '<span class="badge badge-red">administrator</span>';

                            if($type == 2 || $type == 3)
                                echo "<span class='badge badge-red' style = 'margin-left: 5px; cursor: pointer;' onclick = 'delete_order_chat(".$messages[$x]['id'].")'>Remove</span>";

                            echo '</span>';
                            echo '<span class="time">'.date("d M Y g:i:sA", $messages[$x]['timestamp']).'</span>';
                            echo '</div>'.stripslashes($messages[$x]['message']).'</li>';
                            echo '<li class="divider"></li>';
                        }
                        else if($messages[$x]['type'] == 3)
                        {
                            echo '<li class="arrow-box-left gray" id="msg-'.$messages[$x]['id'].'">';
                            echo '<div class="avatar"><img class="avatar-small" src="images/avatars/'.$messages[$x]['type'].'.png"></div>';
                            echo '<div class="info"><span class="name"><strong>'.$messages[$x]['name'].'</strong>';
                            echo '<span class="badge badge-red">manager</span>';

                            if($type == 2 || $type == 3)
                                echo "<span class='badge badge-red' style = 'margin-left: 5px; cursor: pointer;' onclick = 'delete_order_chat(".$messages[$x]['id'].")'>Remove</span>";

                            echo '</span>';
                            echo '<span class="time">'.date("d M Y g:i:sA", $messages[$x]['timestamp']).'</span>';
                            echo '</div>'.stripslashes($messages[$x]['message']).'</li>';
                            echo '<li class="divider"></li>';
                        }

                        $x++;
                    }
                    ?>

                </div>
            </ul>
        </div>

        <div class="box-footer flat padded" style = "height: auto">
            <?php
            echo '
            <div class="input-append" style="width: 100%; float:left; position: relative; height:auto">
               <input type="text" name="msg-box" id="msg-box"  style="height: 100%; padding:5px;margin-bottom:10px;
width: 100%; float:left; position: relative; " onkeyup = "check_chat_send(event)">
			   <input type="hidden" id="order" value="'.$order.'" />
               <ul class="add-on" style = "width: 100%; float:left; position: relative;">';
            if($type == 2 || $type == 3)
            {
                $canned_result = mysql_query("SELECT * FROM canned_message WHERE level = 2 ORDER BY defined_order");

                $select_buffer = '<select style="width: 100%; float:left; position: relative;" id = "admin_message"><option value = "0">Custom (enter above)</option>';

                while($canned_row = mysql_fetch_array($canned_result))
                {
                    $select_buffer .= "<option value = '".$canned_row['id']."'>".$canned_row['name']."</options>";
                }

                $select_buffer .= "</select>";

               // echo '<li>'.$select_buffer.'</li>';
            }
            if($type == 1 || $type == 2 || $type == 3)
            {
                $canned_result = mysql_query("SELECT * FROM canned_message WHERE level = 1 ORDER BY defined_order");

                $select_buffer = '<select id = "booster_message"><option value = "0">Custom (enter above)</option>';

                while($canned_row = mysql_fetch_array($canned_result))
                {
                    $select_buffer .= "<option style='width: 100%; float:left; position: relative;' value = '".$canned_row['id']."'>".$canned_row['name']."</options>";
                }

                $select_buffer .= "</select>";

               // echo '<li>'.$select_buffer.'</li>';
            }

            echo '
                  <li>
                     <button class="btn btn-success" style="margin-bottom: 10px; height: 26px" type="submit" onclick = "chat_send()">Send</button>
                  </li>
               </ul>
            </div>';

            ?>
        </div>
    </div>
</div>
</div>
</div>
  <!-- <div class="col-lg-6">
      <div class="box stats">
         <div class="box-header">
            <span class="title">Top 3 Champions</span>
         </div>
         <div class="box-content padded">
            <div id="bar-champ" style="width: 100%; height: 400px"></div>
         </div>
      </div>
   </div>
   <script>
      var tt = document.createElement('div'),
      leftOffset = -(~~$('html').css('padding-left').replace('px', '') + ~~$('body').css('margin-left').replace('px', '')),
      topOffset = -32;
      tt.className = 'ex-tooltip';
      document.body.appendChild(tt);

      var data = {
         "xScale": "ordinal",
         "yScale": "linear",
         "main": [
            {
      "className": ".played",
			"data": [
        {
          "x": "1. <?php echo $champ_lookup[key_to_name($champ_lookup, (string)$champ_keys[0])]['name'] ?>",
          "y": <?php if($champs[$champ_keys[0]] != null) echo $champs[$champ_keys[0]]; else echo "0"; ?>
        },
        {
          "x": "2. <?php echo $champ_lookup[key_to_name($champ_lookup, (string)$champ_keys[1])]['name'] ?>",
          "y": <?php if($champs[$champ_keys[1]] != null) echo $champs[$champ_keys[1]]; else echo "0"; ?>
        },
        {
          "x": "3. <?php echo $champ_lookup[key_to_name($champ_lookup, (string)$champ_keys[2])]['name'] ?>",
          "y": <?php if($champs[$champ_keys[1]] != null) echo $champs[$champ_keys[2]]; else echo "0"; ?>
        },]
    },{
      "className": ".wins",
			"data": [
        {
          "x": "1. <?php echo $champ_lookup[key_to_name($champ_lookup, (string)$champ_keys[0])]['name'] ?>",
          "y": <?php if($win_loss[0]['win'] != null) echo $win_loss[0]['win']; else echo "0"; ?>
        },
        {
          "x": "2. <?php echo $champ_lookup[key_to_name($champ_lookup, (string)$champ_keys[1])]['name'] ?>",
          "y": <?php if($win_loss[1]['win'] != null) echo $win_loss[1]['win']; else echo "0"; ?>
        },
        {
          "x": "3. <?php echo $champ_lookup[key_to_name($champ_lookup, (string)$champ_keys[2])]['name'] ?>",
          "y": <?php if($win_loss[2]['win'] != null) echo $win_loss[2]['win']; else echo "0"; ?>
        },]
    },{
      "className": ".losses",
			"data": [
        {
          "x": "1. <?php echo $champ_lookup[key_to_name($champ_lookup, (string)$champ_keys[0])]['name'] ?>",
          "y": <?php if($win_loss[0]['loss'] != null) echo $win_loss[0]['loss']; else echo "0"; ?>
        },
        {
          "x": "2. <?php echo $champ_lookup[key_to_name($champ_lookup, (string)$champ_keys[1])]['name'] ?>",
          "y": <?php if($win_loss[1]['loss'] != null) echo $win_loss[1]['loss']; else echo "0"; ?>
        },
        {
          "x": "3. <?php echo $champ_lookup[key_to_name($champ_lookup, (string)$champ_keys[2])]['name'] ?>",
          "y": <?php if($win_loss[2]['loss'] != null) echo $win_loss[2]['loss']; else echo "0"; ?>
        },]
    },         ]
      };

      var opts = {
         "tickFormatY": function (x) { if(Math.round(x) == x) return x; else return ""; },
         "mouseover": function (d, i) {
            var klasa = $(this).parent().attr('class');
            var klasa = klasa.substr(6,4);
		
            var pos = $(this).offset();
            if(klasa == "wins")
               $(tt).text('Wins: ' + d.y)
            else if(klasa == "play")
               $(tt).text('Total Played: ' + d.y)
            else if(klasa == "loss")
               $(tt).text('Losses: ' + d.y)
         
            $(tt).css({top: topOffset + pos.top, left: pos.left + leftOffset}).show();
         },
         "mouseout": function (x) {
            $(tt).hide();
         }
      };
      
      var myChart = new xChart('bar', data, '#bar-champ', opts);
      $('.details .box-content').css({
         'height': $('.stats .box-content').height()
      });
			
      var currentId = 7862;

   </script>
</div>    -->
<!-- match history box -->
<div class="row-fluid">
   <div class="col-lg-12" style = "width: 100%; margin:0 auto; ">
      <div class="box details" style="margin-bottom: -1px;">
         <div class="box-header">
            <span class="title">Match History</span>
            <ul class="box-toolbar">            
               <li><span class="label label-green"></span></li>
            </ul>
         </div>
         <div class="box-content">
            <div id="">
   <table class="table table-bordered table-striped table-hover">
      <thead>
         <tr>
            <th style = "padding-left: 10px;" width = "70px">Result</th>
            <th width="72px">Champion</th>
            <th width = "250px">Details</th>
            <th width = "120px">Spells</th>
            <th width = "120px">Items</th>
            <th width = "80px">KDA</th>
            <th width = "70px">Minions</th>
            <th width = "70px">Gold</th>
			<th width = "70px" style = "padding-right: 10px;">Booster</th>
         </tr>
      </thead>
      <style>
         .match_loss {
            background-color: #690019;
            background: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(0, #690019), color-stop(1.0, #4F0011));
            background: -webkit-linear-gradient(center top, #690019 0%, #4F0011 100%);
            background: -moz-linear-gradient(center top, #690019 0%, #4F0011 100%);
            background: -ms-linear-gradient(center top, #690019 0%, #4F0011 100%);
            background: -o-linear-gradient(center top, #690019 0%, #4F0011 100%);
            color: white;
			border: 5px solid #333;
			width: 1020px;
			text-align: center;
			height: 91px;
			margin: 5px;
			border: 1px solid #222222;
			box-shadow: 0 0 2px #000000 inset;
			overflow: hidden;
         }
         
         .match_win {
            background-color: #00611A;
            background: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(0, #00611A), color-stop(1.0, #004D14));
            background: -webkit-linear-gradient(center top, #00611A 0%, #004D14 100%);
            background: -moz-linear-gradient(center top, #00611A 0%, #004D14 100%);
            background: -ms-linear-gradient(center top, #00611A 0%, #004D14 100%);
            background: -o-linear-gradient(center top, #00611A 0%, #004D14 100%);
            color: white;
			border: 5px solid #333;
			width: 1020px;
			text-align: center;
			height: 91px;
			margin: 5px;
			border: 1px solid #222222;
			box-shadow: 0 0 2px #000000 inset;
			overflow: hidden;
         }
		 
		 .match_owner {
            background-color: #0066AA;
            background: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(0.5, #0066AA), color-stop(1.0, #00416D));
            background: -webkit-linear-gradient(center top, #0066AA 0%, #00416D 100%);
            background: -moz-linear-gradient(center top, #0066AA 0%, #00416D 100%);
            background: -ms-linear-gradient(center top, #0066AA 0%, #00416D 100%);
            background: -o-linear-gradient(center top, #0066AA 0%, #00416D 100%);
            color: white;
			width: 100%;
         }
         .summoner-spells img {
            width: 32px;
            height: 32px;
         }
		 #match_history {
			background-color: #333333;
			padding: 5px;
			width: 100%;
		 }
		 td {
			border: none !important;
		 }
		 #match_holder {
			position: relative;
			width: 100%;
			background: #333;
			margin: auto;
			box-shadow: 0px 0px 2px #000000;
			overflow: hidden;
		 }
		 .result {
		    position: relative;
			float: left;
			width: 70px;
			height: 100%;
			text-align: center;
			line-height: 7;
			padding-left: 5px;
			padding-right: 5px;
		 }
		 .champion {
		    position: relative;
			float: left;
			width: 72px;
			height: 100%;
			margin-top: 9px;
			padding-left: 5px;
			padding-right: 5px;
		 }
		 .match_details {
		    position: relative;
			float: left;
			width: 250px;
			text-align: center;
			padding-left: 5px;
			padding-right: 5px;
			margin-top: 19px;
		 }
		 .spells {
			position: relative;
			float: left;
			width: 120px;
			text-align: center;
			padding-left: 5px;
			padding-right: 5px;
			margin-top: 29px;
		 }
		 .spells img {
			width: 32px;
			height: 32px;
		 }
		 .items {
			position: relative;
			float: left;
			width: 120px;
			text-align: center;
			padding-left: 5px;
			padding-right: 5px;
			margin-top: 13px;
		 }
		 .match_stats {
		    position: relative;
			float: left;
			width: 80px;
			text-align: center;
			padding-left: 5px;
			padding-right: 5px;
			margin-top: 20px;
		 }
		 .minions {
		    position: relative;
			float: left;
			width: 70px;
			height: 100%;
			text-align: center;
			line-height: 7;
			padding-left: 5px;
			padding-right: 5px;
		 }
		 .gold {
		    position: relative;
			float: left;
			width: 70px;
			height: 100%;
			text-align: center;
			line-height: 7;
			padding-left: 5px;
			padding-right: 5px;
		 }
		 .booster {
		    position: relative;
			float: left;
			width: 70px;
			height: 100%;
			text-align: center;
			line-height: 7;
			padding-left: 5px;
			padding-right: 5px;
		 }
      </style>
	  </table>
	  <div id = "match_holder">
		<?php
			$x = 0;

			while(isset($returnArray[$x]) && $x < 5)
			{
				if($returnArray[$x]['win'] == 0)
					echo '<div class="match_loss">';
				else
					echo '<div class="match_win">';

				if($returnArray[$x]['win'] == 0)
					echo '<div class="result">Loss</div>';
				else
					echo '<div class="result">Win</div>';

				echo '<div class = "champion"><div style="background-image: url(images/champions/'.$returnArray[$x]['champion'].'.png); background-size: contain; height: 72px; width: 72px;"></div></div>';

				echo '<div class="match_details"><small><i>'.$tier.' '.$rank.', LP: '.$returnArray[$x]['lp_at_end'].'</i></small><br><small>'.$returnArray[$x]['date'].'</small><br><small>'.floor((time() - $returnArray[$x]['timestamp'])/3600).' Hours Ago</small></div>';

				echo '<div class="spells"><img src="images/summoner/'.$returnArray[$x]['spell1'].'.png"><img src="images/summoner/'.$returnArray[$x]['spell2'].'.png"></div>';

				echo '<div class="items">';

				if(isset($returnArray[$x]['item0']) && $returnArray[$x]['item0'] != 0)
				{
					echo '<img src="https://images.weserv.nl/?url=img.lolking.net/shared/riot/images/items/'.$returnArray[$x]['item0'].'_32.png" alt="">';
				}
				if(isset($returnArray[$x]['item1']) && $returnArray[$x]['item1'] != 0)
				{
					echo '<img src="https://images.weserv.nl/?url=img.lolking.net/shared/riot/images/items/'.$returnArray[$x]['item1'].'_32.png" alt="">';
				}
				if(isset($returnArray[$x]['item2']) && $returnArray[$x]['item2'] != 0)
				{
					echo '<img src="https://images.weserv.nl/?url=img.lolking.net/shared/riot/images/items/'.$returnArray[$x]['item2'].'_32.png" alt="">';
				}
				if(isset($returnArray[$x]['item3']) && $returnArray[$x]['item3'] != 0)
				{
					echo '<img src="https://images.weserv.nl/?url=img.lolking.net/shared/riot/images/items/'.$returnArray[$x]['item3'].'_32.png" alt="">';
				}
				if(isset($returnArray[$x]['item4']) && $returnArray[$x]['item4'] != 0)
				{
					echo '<img src="https://images.weserv.nl/?url=img.lolking.net/shared/riot/images/items/'.$returnArray[$x]['item4'].'_32.png" alt="">';
				}
				if(isset($returnArray[$x]['item5']) && $returnArray[$x]['item5'] != 0)
				{
					echo '<img src="https://images.weserv.nl/?url=img.lolking.net/shared/riot/images/items/'.$returnArray[$x]['item5'].'_32.png" alt="">';
				}
				   echo '<br></div>';
				
				echo '<div class="match_stats">'.$returnArray[$x]['kills'].' Kills<br>'.$returnArray[$x]['deaths'].' Deaths<br>'.$returnArray[$x]['assists'].' Assists</div>';

				echo '<div class="minions">'.$returnArray[$x]['minions'].'</div>';

				echo '<div class="gold">'.$returnArray[$x]['gold'].'g</div>';

				echo '<div class="booster">'.$returnArray[$x]['booster'].'</div>';
				//echo '<div class="booster"></div>';

				echo '</div>';

				$x++;
				
				/*if($returnArray[$x]['win'] == 0)
					echo '<tbody class="match_loss" cellpadding="0" cellspacing="0">';
				else
					echo '<tbody class="match_win" cellpadding="0" cellspacing="0">';

				if($returnArray[$x]['win'] == 0)
					echo '<tr><td class="center">Loss</td>';
				else
					echo '<tr><td class="center">Win</td>';

				echo '<td><div style="background-image: url(images/champions/'.$returnArray[$x]['champion'].'.png); background-size: contain; height: 72px; width: 72px;"></div></td>';

				echo '<td class="center"><small><i>'.$tier.' '.$rank.', LP: '.$returnArray[$x]['lp_at_end'].'</i></small><br><small>'.$returnArray[$x]['date'].'</small><br><small>'.floor((time() - strtotime($returnArray[$x]['date']))/360).' Hours Ago</small></td>';

				echo '<td class="center summoner-spells"><img src="images/summoner/'.$returnArray[$x]['spell1'].'.png"><img src="images/summoner/'.$returnArray[$x]['spell2'].'.png"></td>';

				echo '<td class="center">';

				if(isset($returnArray[$x]['item0']) && $returnArray[$x]['item0'] != 0)
				{
					echo '<img src="https://images.weserv.nl/?url=img.lolking.net/shared/riot/images/items/'.$returnArray[$x]['item0'].'_32.png" alt="">';
				}
				if(isset($returnArray[$x]['item1']) && $returnArray[$x]['item1'] != 0)
				{
					echo '<img src="https://images.weserv.nl/?url=img.lolking.net/shared/riot/images/items/'.$returnArray[$x]['item1'].'_32.png" alt="">';
				}
				if(isset($returnArray[$x]['item2']) && $returnArray[$x]['item2'] != 0)
				{
					echo '<img src="https://images.weserv.nl/?url=img.lolking.net/shared/riot/images/items/'.$returnArray[$x]['item2'].'_32.png" alt="">';
				}
				if(isset($returnArray[$x]['item3']) && $returnArray[$x]['item3'] != 0)
				{
					echo '<img src="https://images.weserv.nl/?url=img.lolking.net/shared/riot/images/items/'.$returnArray[$x]['item3'].'_32.png" alt="">';
				}
				if(isset($returnArray[$x]['item4']) && $returnArray[$x]['item4'] != 0)
				{
					echo '<img src="https://images.weserv.nl/?url=img.lolking.net/shared/riot/images/items/'.$returnArray[$x]['item4'].'_32.png" alt="">';
				}
				if(isset($returnArray[$x]['item5']) && $returnArray[$x]['item5'] != 0)
				{
					echo '<img src="https://images.weserv.nl/?url=img.lolking.net/shared/riot/images/items/'.$returnArray[$x]['item5'].'_32.png" alt="">';
				}
				   echo '<br></td>';
				
				echo '<td class="center">'.$returnArray[$x]['kills'].' Kills<br>'.$returnArray[$x]['deaths'].' Deaths<br>'.$returnArray[$x]['assists'].' Assists</td>';

				echo '<td class="center">'.$returnArray[$x]['minions'].'</td>';

				echo '<td class="center">'.$returnArray[$x]['gold'].'g</td>';

				echo '<td class="center">'.$returnArray[$x]['booster'].'</td>';

				$x++;*/
			}
				?>
	 </div>
	         
                        
</div>         </div>
      </div>
                        <div class="box">
            <div class="box-header">
               <div class="pagination pagination-centered pagination-small">
                  <div id="page-selection" class="pagination"></div>
               </div>
            </div>
         </div>
         <script>
   $('#page-selection').bootpag({
      total: <?php echo $pages; ?>,
      page: 1
   }).on('page', function(event, num) {
		var ajaxHandler = new XMLHttpRequest();

		ajaxHandler.onreadystatechange = function ()
		{
			if(ajaxHandler.readyState == 4)
			{
				//console.log(ajaxHandler.responseText);
				var content = document.getElementById("match_holder");
				content.innerHTML = ajaxHandler.responseText;
			}
		}

		ajaxHandler.open("POST", "history.php", true);
		ajaxHandler.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		ajaxHandler.send("page="+num+"&order=<?php echo $order; ?>");
   });
</script>
         </div>
</div>

   
   <?php
	//	include("facebook.php");
   ?>
   <?php
	if($type == 2 || $type == 3)
	{
?>
    <!--
<div class="row-fluid">
   <div class="col-lg-12">
      <div class="box">
         <div class="box-header">
            <span class="title">Email Notifications</span>
         </div>
         <div class="box-content">
            <table class="table table-normal">
               <thead>
                  <tr>
					 <td>Name</td>
					 <td>Action</td>
                  </tr>
               </thead>
               <tbody>
			   <form method = 'post' action = 'send_email_notification.php'>
			   <input type = "hidden" value = "<?php echo $order; ?>" name = "order" />
			   <tr><td><select name = "message">
			   <?php
					$result = mysql_query("SELECT * FROM email_notification ORDER BY defined_order");

					while($row = mysql_fetch_array($result))
					{
						echo "<option value = '".$row['id']."'>".$row['name']."</option>";
					}
			   ?>
			   </select></td>
			   <td><input type = 'submit' class='btn btn-success btn-xs' value = 'Send' /></td>
			   </form>
			   </tbody>
            </table>
         </div>
      </div>
   </div>
</div> -->
<?php
	}
?>
<?php
	if($type == 2 || $type == 3)
	{
?>
<div class="row-fluid">
   <div class="col-lg-12">
      <div class="box">
         <div class="box-header">
            <span class="title">Claim Log</span>
         </div>
         <div class="box-content">
            <table class="table table-bordered table-striped table-hover">
               <thead>
                  <tr>
					 <th>Booster</th>
					 <th>Date Claimed</th>
					 <th>Date Unclaimed</th>
                  </tr>
               </thead>
               <tbody>
			   <?php
					$result = mysql_query("SELECT * FROM booster_order WHERE order_record = $order ORDER BY timestamp DESC");

					while($row = mysql_fetch_array($result))
					{
						$subresult = mysql_query("SELECT * FROM user WHERE id = ".$row['booster']);
						$subrow = mysql_fetch_array($subresult);
						echo "<tr><td>".$subrow['username']."</td>";
						echo "<td>".date("n-j-Y g:iA", $row['timestamp'])."</td>";
						if($row['unclaim_time'] == NULL || $row['unclaim_time'] == "")
							echo "<td>Still claimed</td></tr>";
						else
							echo "<td>".date("n-j-Y g:iA", $row['unclaim_time'])."</td></tr>";
					}
			   ?>		 
			   </tbody>
            </table>
         </div>
      </div>
   </div>
</div>
<?php
	}
?>
</div>
<script>
function check_chat_send (event)
{
	if(event.keyCode == 13)
	{
		if(document.getElementById("msg-box").value != "")
		{
			chat_send();
		}
	}
}
function chat_send ()
{
	if(document.getElementById("msg-box").value != "")
	{
		var ajaxHandler = new XMLHttpRequest();

		ajaxHandler.onreadystatechange = function ()
		{
			if(ajaxHandler.readyState == 4)
			{
				update_order_chat();
				document.getElementById("msg-box").value = "";
			}
		}

		var form = new FormData();
		form.append("msg-box", document.getElementById("msg-box").value);
		form.append("order", document.getElementById("order").value);

		ajaxHandler.open("POST", "chat-reply.php");
		ajaxHandler.send(form);
	}
	else
	{
		if(document.getElementById("admin_message") != null)
		{
			if(document.getElementById("admin_message").value != "0")
			{
				console.log(document.getElementById("admin_message").value)
				var ajaxHandler = new XMLHttpRequest();

				ajaxHandler.onreadystatechange = function ()
				{
					if(ajaxHandler.readyState == 4)
					{
						update_order_chat();
						document.getElementById("msg-box").value = "";
					}
				}

				var form = new FormData();
				form.append("canned", document.getElementById("admin_message").value);
				form.append("order", document.getElementById("order").value);

				ajaxHandler.open("POST", "chat-reply.php");
				ajaxHandler.send(form);
			}
			else if(document.getElementById("booster_message").value != "0")
			{
				var ajaxHandler = new XMLHttpRequest();

				ajaxHandler.onreadystatechange = function ()
				{
					if(ajaxHandler.readyState == 4)
					{
						update_order_chat();
						document.getElementById("msg-box").value = "";
					}
				}

				var form = new FormData();
				form.append("canned", document.getElementById("booster_message").value);
				form.append("order", document.getElementById("order").value);

				ajaxHandler.open("POST", "chat-reply.php");
				ajaxHandler.send(form);
			}
		}
		else if(document.getElementById("booster_message").value != "0")
			{
				var ajaxHandler = new XMLHttpRequest();

				ajaxHandler.onreadystatechange = function ()
				{
					if(ajaxHandler.readyState == 4)
					{
						update_order_chat();
						document.getElementById("msg-box").value = "";
					}
				}

				var form = new FormData();
				form.append("canned", document.getElementById("admin_message").value);
				form.append("order", document.getElementById("order").value);

				ajaxHandler.open("POST", "chat-reply.php");
				ajaxHandler.send(form);
			}

	}
}
function delete_order_chat (id)
{
	var ajaxHandler = new XMLHttpRequest();

	var form = new FormData();
	form.append("id", id);

	ajaxHandler.open("POST", "delete_order_chat.php");
	ajaxHandler.send(form);

	var target = document.getElementById("msg-"+id);
	target.parentNode.removeChild(target);
}
function update_order_chat ()
{
	var ajaxHandler = new XMLHttpRequest();

	ajaxHandler.onreadystatechange = function ()
	{
		if(ajaxHandler.readyState == 4)
		{
			var chat_box = document.getElementById("chat-messages-inner");

			var messages = eval( '(' + ajaxHandler.responseText + ')' );

			var i = 0;

			chat_box.innerHTML = "";
			var html_buffer = "";

			while(messages[i] != null)
			{
				if(messages[i]['type'] != 0)
				{
					html_buffer += '<li class="arrow-box-left gray" id="msg-'+messages[i]['id']+'">';
					html_buffer += '<div class="avatar"><img class="avatar-small" src="images/avatars/'+messages[i]['type']+'.png"></div>';
					html_buffer += '<div class="info"><span class="name"><strong>'+messages[i]['name']+'</strong>';

					if(messages[i]['type'] == 2)
						html_buffer += '<span class="badge badge-red">administrator</span>';
					else if(messages[i]['type'] == 3)
						html_buffer += '<span class="badge badge-red">manager</span>';
					else
						html_buffer += '<span class="badge badge-blue">booster</span>';

					<?php
						if($type == 2 || $type == 3)
							echo "html_buffer += '<span class=\"badge badge-red\" style = \"margin-left: 5px; cursor: pointer;\" onclick = \"delete_order_chat('+messages[i]['id']+')\">Remove</span>';";
					?>

					html_buffer += '</span><span class="time">'+messages[i]['time']+'</span></div>';
					html_buffer += messages[i]['message'];
					html_buffer += '</li><li class="divider"></li>';
				}
				else
				{
					html_buffer += '<li class="arrow-box-right gray" id="msg-'+messages[i]['id']+'">';
					html_buffer += '<div class="avatar"><img class="avatar-small" src="images/avatars/'+messages[i]['type']+'.png"></div>';
					html_buffer += '<div class="info"><span class="name"><strong>'+messages[i]['name']+'</strong>';
					html_buffer += '<span class="badge badge-gray">customer</span>';
					<?php
						if($type == 2 || $type == 3)
							echo "html_buffer += '<span class=\"badge badge-red\" style = \"margin-left: 5px; cursor: pointer;\" onclick = \"delete_order_chat('+messages[i]['id']+')\">Remove</span>';";
					?>
					html_buffer += '</span><span class="time">'+messages[i]['time']+'</span></div>';
					html_buffer += messages[i]['message'];
					html_buffer += '</li><li class="divider"></li>';
				}
				i++;
			}

			chat_box.innerHTML = html_buffer;
		}
	}
	
	var form = new FormData();
	form.append("order", <?php echo $order; ?>);

	ajaxHandler.open("POST", "order-chat-refresh.php");
	ajaxHandler.send(form);
}
function updateTimer ()
{
	update_order_chat();
	update_match_history();
	setTimeout(updateTimer, 10000);
}
function updateMatches ()
{
	update_matches();
	setTimeout(updateMatches, 10000);
}
var timestamp = <?php echo $returnArray[0]['timestamp'] ? $returnArray[0]['timestamp'] != null : 0; ?>;
function update_matches ()
{
	var ajaxHandler = new XMLHttpRequest();

	ajaxHandler.onreadystatechange = function ()
	{
		if(ajaxHandler.readyState == 4)
		{
			console.log(ajaxHandler.responseText);
			if(!isNaN(ajaxHandler.responseText))
			{
				timestamp = ajaxHandler.responseText;
			}
		}
	}

	var form = new FormData();

	form.append("id", <?php echo $order; ?>);
	form.append("timestamp", timestamp);

	ajaxHandler.open("POST", "match-check.php");
	ajaxHandler.send(form);
}
window.onload = function ()
{
	updateTimer();

	<?php /*if($booster == $username)
		echo "updateMatches();";*/
	?>
}
function check_confirm (event)
{
	if(!confirm("Are you sure?"))
	{
		event.preventDefault();
		return false;
	}
}
function check_specified (event)
{
	if(document.getElementById("booster-name").value == 0)
	{
		alert("Please select a booster.");
		event.preventDefault();
		return false;
	}
}
function update_match_history ()
{
	var ajaxHandler = new XMLHttpRequest();

	ajaxHandler.onreadystatechange = function ()
	{
		if(ajaxHandler.readyState == 4)
		{
			document.getElementById("match_holder").innerHTML = ajaxHandler.responseText;
		}
	}

	var form = new FormData();

	form.append("id", <?php echo $order; ?>);

	ajaxHandler.open("POST", "match_history_refresh.php");
	ajaxHandler.send(form);
}
</script>
</div>

<?php
	include("bottom.php");
?>




